var fs = require('fs');
var path = require('./path');

var routesRoot = null;
var routesWork = null;

function recursiveRoutes(app, dirName) {
    fs.readdirSync(dirName).forEach(function (file) {
        var fileName = dirName + "/" + file;
        var stat = fs.statSync(fileName);

        if (stat.isDirectory()) {
            recursiveRoutes(app, fileName);
        } else if (getSuffixName(file.toLowerCase()) == ".js") {
            app.use(getRoutePath(fileName), require(getRouteFile(fileName)));
        }
    });
}

function getSuffixName(fileName) {
    var index1 = fileName.lastIndexOf(".");
    var index2 = fileName.length;
    return fileName.substring(index1, index2);
}

function getRouteFile(fileName) {
    if (routesWork) {
        return path.normalize(routesWork + '/' + fileName.substr(routesRoot.length));
    } else {
        return fileName.substr(routesRoot.length);
    }
}

function getRoutePath(fileName) {
    var fileOl = path.parse(fileName);
    var retval = fileOl.dir.substr(routesRoot.length).split(path.sep).join('/');
    return retval.length ? retval : "/";
}

function getRoutePathEx(fileName) {
    var fileOl = path.parse(fileName);
    var retval = fileOl.dir.substr(routesRoot.length).split(path.sep).join('/');
    retval = retval.length ? retval : "/";
    return fileOl.name == 'index' ? retval : retval + "/" + fileOl.name;
}

module.exports.loads = function (app, _routesRoot, _routesWork) {
    routesRoot = _routesRoot;
    routesWork = _routesWork;
    recursiveRoutes(app, _routesRoot);
};

module.exports.load = function (app, file, path) {
    app.use(path, require(file));
}